<!-- subpkg_consult/room/index.vue -->
<script setup>
	import { io } from 'socket.io-client'
	import { useUserStore } from '@/stores/index.js'
	import { ref } from 'vue'
	// 引入患者信息列表
	import patientInfo from './components/patient-info.vue'
	import notifyInfo from './components/notify-info.vue'
	import messageInfo from './components/message-info.vue'
	import prescriptionInfo from './components/prescription-info.vue'
	import rateInfo from './components/rate-info.vue'
	import roomStatus from './components/room-status.vue'
	import { orderDetailAPI } from '../../apis/consult'
import dayjs from 'dayjs'
	const store = useUserStore()
	// 获取query身上的orderId
	const props = defineProps({
		orderId: String
	})
	// 建立 socket 连接
	const socket = io('https://consult-api.itheima.net', {
		auth: { token: 'Bearer ' + store.user.token },
		query: { orderId: props.orderId }
	})

	// 消息列表
	const messageList = ref([])

	// 获取历史聊天记录
	socket.on('chatMsgList', (res) => {
		// 关闭动画
		refresherTriggered.value = false
		console.log(res, 22222)

		// 定义一个临时的数组 保存分段的数据
		const tempData = []
		res.data.forEach((v,index) => {
			// 判断数组的第一条元素
			if (index === 0) lastTime.value = v.createTime
			tempData.push(
				// 构造分段的时间
				{
					msgType: 31, // 消息的类型
					msg: { content: v.createTime }, // 消息的内容
					id: v.createTime
				},
				...v.items
			)
			// messageList.value.push(...v.items)
		})
		// 如果没有历史聊天记录 提示
		if (tempData.length === 0) return uni.showToast({
			icon: 'none',
			title: '没有历史聊天记录'
		})
		
		messageList.value.unshift(...tempData)
	})

	// 接收消息是用 on方法 发送消息用 emit
	// 获取医生消息通知
	socket.on('receiveChatMsg', (message) => {
		// 将当前的这条消息修改为已读
		socket.emit('updateMsgStatus', message.id)
		// console.log(message, 11111)
		messageList.value.push(message)
	})

	// 获取医生的详情数据
	const orderDetailInfo = ref()
	const orderDetail = async () => {
		const res = await orderDetailAPI(props.orderId)
		// console.log(res, 11111)
		orderDetailInfo.value = res.data
	}
	orderDetail()

	// 监听客户端状态的变化
	socket.on('statusChange', orderDetail)
	// 输入框内容
	const textMessage = ref('')
	// 发送文字聊天
	const onInputConfirm = () => {
		// 使用socket.emit('事件名', 参数)
		socket.emit('sendChatMsg', {
			from: store.user.id,
			to: orderDetailInfo.value.docInfo.id,
			msgType: 1,
			msg: {
				content: textMessage.value
			}
		})
		// 清空输入框的文本
		textMessage.value = ''
	}

	// 选择图片
	const onImageUpload = () => {
		// 判断是否接诊中
		if (orderDetailInfo.value.status !== 3) {
			return uni.showToast({
				icon: 'none',
				title: '当前医生还未接诊'
			})
		}
		// 需要上传图片
		uniCloud.chooseAndUploadFile({
			type: 'image',
			count: 1,
			extension: ['.jpg', '.webp', '.png', '.jpeg', '.gif'],
			success: (res) => {
				// console.log(res.tempFiles[0])
				// 图片的数据
				const pictures = {
					id: res.tempFiles[0].lastModified,
					url: res.tempFiles[0].url
				}
				// 使用 socke.emit方法将图片发送给服务器
				socket.emit('sendChatMsg', {
					from: store.user.id,
					to: orderDetailInfo.value.docInfo.id,
					msgType: 4,
					msg: {
						picture: pictures
					}
				})
			}
		})
	}
	// 获取当前时间
	const lastTime = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))


	// 设置当前下拉刷新状态，true 表示下拉刷新已经被触发，false 表示下拉刷新未被触发
	const refresherTriggered = ref(false)
	// 下拉刷新
	const onRefresherrefresh = () => {
		// console.log('okok')
		refresherTriggered.value = true
		// 聊天-查询历史聊天记录
		socket.emit('getChatMsgList', 20, lastTime.value, props.orderId); 
		
	}
</script>

<template>
	<view class="room-page">
		<scroll-view
			@refresherrefresh="onRefresherrefresh"
			refresher-enabled
			refresher-background="#f2f2f2"
			:refresher-triggered="refresherTriggered"
			scroll-y
			style="flex: 1; overflow: hidden"
		>
			<!-- 问诊的状态 1.状态 2.状态的值 3.倒计时的时间  -->
			<roomStatus
				:status="orderDetailInfo?.status"
				:countdown="orderDetailInfo?.countdown"
				:statusValue="orderDetailInfo?.statusValue"
			></roomStatus>
			<view class="message-container">
				<!-- 此处将来填充更多代码... -->
				<template v-for="item in messageList" :key="item.id">
					<!-- 患者消息 -->
					<patient-info
						v-if="item.msgType === 21"
						:info="item.msg.consultRecord"
					></patient-info>
					<!-- 通知消息 -->
					<notify-info
						v-if="item.msgType >= 31"
						:msgType="item.msgType"
						:msg="item.msg.content"
					>
					</notify-info>
					<!-- 文字/图片消息 -->
					<message-info
						v-if="item.msgType <= 4"
						:msgType="item.msgType"
						:message="item"
					></message-info>
					<!-- 处方信息 -->
					<prescription-info
						v-if="item.msgType === 22"
						:info="item.msg.prescription"
					></prescription-info>
					<!-- 医生评价 -->
					<rate-info
						v-if="item.msgType === 23"
						:order-id="props.orderId"
						:doctor-id="orderDetailInfo?.docInfo.id"
						:hasEvaluate="false"
					></rate-info>

					<rate-info
						v-if="item.msgType === 24"
						:hasEvaluate="true"
						:eva-msg="item.msg.evaluateDoc"
					></rate-info>
				</template>
			</view>
		</scroll-view>

		<!-- 发送消息 -->
		<view class="message-bar">
			<template v-if="true">
				<uni-easyinput
					@confirm="onInputConfirm"
					:disabled="orderDetailInfo?.status !== 3"
					:clearable="false"
					:input-border="false"
					placeholder-style="font-size: 32rpx; color: #c3c3c5;"
					placeholder="问医生"
					v-model="textMessage"
				/>
				<view class="image-button" @click="onImageUpload">
					<uni-icons size="40" color="#979797" type="image"></uni-icons>
				</view>
			</template>
			<button v-else class="uni-button">咨询其它医生</button>
		</view>
	</view>
</template>

<style lang="scss">
	@import './index.scss';
</style>
